﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ScreenMonitor.Common
{
    /// <summary>
    /// 为可发送对象提供接口
    /// </summary>
    public interface ISendableObject
    {
        /// <summary>
        /// 将对象转化为字节数组
        /// </summary>
        /// <returns></returns>
        byte[] ToByte();
        /// <summary>
        /// 从字节数组初始化对象
        /// </summary>
        /// <param name="Buffer"></param>
        /// <returns></returns>
        void InitFormByte(byte[] Buffer);
    }

    /// <summary>
    /// 为可通过流读写器序列化的可发送对象提供接口
    /// </summary>
    public interface IStreamSendableObject
    {
        /// <summary>
        /// 向指定的流写入器写入对象数据
        /// </summary>
        /// <param name="sw">要写入数据的流写入器</param>
        void ToStream(BinaryWriter sw);
        /// <summary>
        /// 从指定的流读取器读取数据到对象
        /// </summary>
        /// <param name="sr">提供要读取的数据的流读取器</param>
        void FromStream(BinaryReader sr);
    }

    /// <summary>
    /// 为可发送对象提供静态构造方法
    /// </summary>
    /// <typeparam name="T">要包装的可发送对象类型</typeparam>
    public class StaticSendableObjectBase<T> where T : ISendableObject, new()
    {
        /// <summary>
        /// 从指定的字节数组构造新的对象实例
        /// </summary>
        /// <param name="Buffer">指定的字节数组</param>
        /// <returns>构造的实例</returns>
        public static T FromByte(byte[] Buffer)
        {
            T obj = new T();
            obj.InitFormByte(Buffer);
            return obj;
        }

    }

    /// <summary>
    /// 为基于MemoryStream序列化的可发送对象提供基类
    /// </summary>
    public abstract class MemoryStreamSendableObjectBase<T> :StaticSendableObjectBase<T>,ISendableObject,IStreamSendableObject where T:ISendableObject,new()
    {

        /// <summary>
        /// 将基础对象转化为字节数组
        /// </summary>
        /// <returns>转化完毕的字节数组</returns>
        public byte[] ToByte()
        {
            MemoryStream stream = new MemoryStream();
            BinaryWriter sw = new BinaryWriter(stream);
            this.ToStream(sw);
            sw.Flush();
            byte[] Buffer = stream.ToArray();
            sw.Close();
            return Buffer;
        }

        /// <summary>
        /// 从指定字节数组初始化基础对象
        /// </summary>
        /// <param name="Buffer">用来初始化对象的Buffer</param>
        public void InitFormByte(byte[] Buffer)
        {
            MemoryStream stream = new MemoryStream(Buffer);
            BinaryReader sr = new BinaryReader(stream);
            this.FromStream(sr);
            sr.Close();
        }

        public abstract void ToStream(BinaryWriter sw);

        public abstract void FromStream(BinaryReader sr);

    }

}
